from zentao.settings import AES_key

import base64
from Crypto.Cipher import AES


class MyAES:
    def __init__(self):
        self.key = AES_key
        self.aes = AES.new(self.add_to_16(self.key), AES.MODE_ECB)

    # str不是16的倍数那就补足为16的倍数
    def add_to_16(self,content):
        while len(content) % 16 != 0:
            content += '\0'
        return str.encode(content)  # 返回bytes

    def encrypted(self,content):
        """
        加密
        """
        return str(base64.encodebytes(self.aes.encrypt(self.add_to_16(content))), encoding='utf8').replace('\n', '')  # 加密

    def decrypted(self,content):
        """
        解密
        """
        return str(self.aes.decrypt(base64.decodebytes(bytes(content, encoding='utf8'))).rstrip(b'\0').decode("utf8"))


# if __name__ == '__main__':
#     text = 'abc123def456'  # 待加密文本
#     aes = MyAES()
#
#     encrypted_text = aes.encrypted(text)
#
#     decrypted_text = aes.decrypted(encrypted_text)
#
#     print('加密值：', encrypted_text)
#
#     print('解密值：', decrypted_text)
#
#     #随机生成秘钥
#     import string, random
#     def generate_complex_key(length):
#         # 定义一个包含大小写字母、数字和常见符号的字符集
#         characters = list(string.ascii_letters + string.digits + string.punctuation)
#         random.shuffle(characters)
#         # 随机选择字符生成秘钥
#         key = ''.join(characters[:32])
#         return key
#
#
#     # 生成一个192位的秘钥（每字符大约6位，所以需要32个字符）
#     complex_key = generate_complex_key(32)
#     print(complex_key)